package org.marverse.universe.modules

import scala.collection.Map
import scala.collection.mutable.HashMap
import util.{MutableTypedMap, TypedKey}

class Modules private (val rootModule: Module) extends UniverseExtension {
  
  def check(implicit ctx: MutableTypedMap[TypedKey, Any]){
    modules.keys foreach { _.check }
  } 
  
  private val mutableModules = HashMap[Module, Module.State]()
  val modules: Map[Module, Module.State] = mutableModules.readOnly

  private def this(universe: Universe) {
    this(new Module(universe.persistentStore.newPId))
    mutableModules += ((rootModule, new Module.State()))
  }
  private def this(previous: Modules) {
    this(previous.rootModule)
    mutableModules ++= previous.modules map { m => (m._1, m._2.advance) }
  }
  
  def apply(module: Module): Module.State = modules(module)

  def advance(advancedUniverse: Universe) = new Modules(this)
  
}

object Modules extends UniverseExtensionProvider(classOf[Modules]) {
  def createExtension(universe: Universe) = new Modules(universe)
}